package com.xtoneict.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xtoneict.auth.entity.*;
import com.xtoneict.auth.entity.param.UserPageParam;
import com.xtoneict.auth.entity.param.UserParam;
import com.xtoneict.auth.service.*;
import com.xtoneict.auth.vo.UserVO;
import com.xtoneict.util.jwt.JwtHelper;
import com.xtoneict.util.result.Result;
import com.xtoneict.util.utils.MD5;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hx
 * @since 2024-05-22
 */
@RestController
@RequestMapping("/auth/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User userOne = userService.getOne(wrapper);
        if(userOne == null){
            throw new RuntimeException("用户不存在");
        }
        String password_db = userOne.getPassword();
        String password_in = MD5.encrypt(user.getPassword());
        if (!password_in.equals(password_db)){
            throw new RuntimeException("密码不正确");
        }

        //查询用户角色
        HashSet<Role> roles = new HashSet<>();
        //查询用户permission
        HashSet<Permission> permissions = new HashSet<>();
        List<Role> roleList = roleService.selectRolesByUserId(userOne.getUserId());
        for (Role role : roleList) {
            roles.add(role);
            List<Permission> permissionList = permissionService.selectPermissionByRoleId(role.getRoleId());
            for (Permission permission : permissionList){
                permissions.add(permission);
            }
        }
        userOne.setRoles(roles);
        userOne.setPermissions(permissions);

        String token = JwtHelper.createToken(userOne.getUserId(), userOne.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user",userOne);

        return Result.ok(map);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }

    /**
     * 根据id获取用户
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    public Result getById(@PathVariable Long id){
        User user = userService.getById(id);
        return Result.ok(user);
    }

    /**
     * 分页查询所有用户
     * @return
     */
    @PostMapping("/page")
    public Result page(@RequestBody UserPageParam userPageParam){
        Integer total = userService.count();
        //如果不分页，则返回全部数据
        if(userPageParam == null || userPageParam.getCurrentPage() == null || userPageParam.getPageSize() == null){
            List<User> users = userService.list();
            List<UserVO> userVOs = new ArrayList<>();
            for (User user : users) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                String depName = departmentService.getById(user.getDepId()).getDepName();
                userVO.setDepName(depName);

                HashSet<Role> roles = new HashSet<>();
                List<Role> roleList = roleService.selectRolesByUserId(user.getUserId());
                for (Role role : roleList){
                    roles.add(role);
                }
                userVO.setRoles(roles);

                userVOs.add(userVO);
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("users", userVOs);

            return Result.ok(map);
        }else {
            //传入分页参数，进行分页查询
            Integer currentPage = userPageParam.getCurrentPage();
            Integer pageSize = userPageParam.getPageSize();
            // 假设要进行无条件的分页查询，每页显示10条记录，查询第1页
            IPage<User> page = new Page<>(currentPage, pageSize);
            IPage<User> userPage = userService.page(page); // 调用 page 方法
            List<User> userList = userPage.getRecords();
            List<UserVO> userVOs = new ArrayList<>();
            for (User user : userList) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                String depName = departmentService.getById(user.getDepId()).getDepName();
                userVO.setDepName(depName);

                HashSet<Role> roles = new HashSet<>();
                List<Role> roleList = roleService.selectRolesByUserId(user.getUserId());
                for (Role role : roleList){
                    roles.add(role);
                }
                userVO.setRoles(roles);

                userVOs.add(userVO);
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("users", userVOs);

            return Result.ok(map);
        }
    }

    /**
     * 保存用户
     * @param userParam
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody UserParam userParam){
        User user = userParam.getUser();
        String passwordMD5 = MD5.encrypt(user.getPassword());
        user.setPassword(passwordMD5);

        boolean is_success = userService.save(user);

        List<Integer> roleIds = userParam.getList();
        roleService.insertRoleAndUser(user.getUserId(), roleIds);

        return Result.ok();
    }

    /**
     * 更新用户
     * @param
     * @return
     */
    @PostMapping("/updateById")
    public Result updateById(@RequestBody UserParam updateUserParam) {
        User user = (User) updateUserParam.getUser();
        List<Integer> roleIds = updateUserParam.getList();
        List<Role> roleList = roleService.listByIds(roleIds);

        roleService.deleteUserAndRole(user.getUserId());

        roleService.insertRoleAndUser(user.getUserId(), roleIds);

        HashSet<Role> roles = new HashSet<>();
        HashSet<Permission> permissions = new HashSet<>();
        for (Role role : roleList){
            roles.add(role);

            List<Permission> permissionList = permissionService.selectPermissionByRoleId(role.getRoleId());
            for (Permission permission : permissionList){
                permissions.add(permission);
            }
        }
        user.setRoles(roles);
        user.setPermissions(permissions);
        boolean is_success = userService.updateById(user);

        if(is_success){
            return Result.ok(user);
        } else {
            return Result.fail();
        }
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        boolean is_success = userService.removeById(id);
        if(is_success){
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

}

